package com.katze.ssh;

import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.AttributeRepository;

import java.io.IOException;
import java.lang.reflect.Constructor;

public class SshSessionEntry implements AutoCloseable{

    private final ClientSession session;
    private final SshSessionKey info;
    private volatile long lastAccessTime;

    public SshSessionEntry(ClientSession session, SshSessionKey info) {
        this.session = session;
        this.info = info;
        this.lastAccessTime = System.currentTimeMillis();
    }

    public String getUsername() {
        return info.getUsername();
    }

    public String getHost() {
        return info.getHost();
    }

    public Integer getPort() {
        return info.getPort();
    }

    public ClientSession getClientSession() {
        return session;
    }

    public void updateLastAccess() {
        this.lastAccessTime = System.currentTimeMillis();
    }

    public boolean isOpen() {
        return session.isOpen();
    }

    public boolean isExpired(long idleTimeout) {
        return System.currentTimeMillis() - lastAccessTime > idleTimeout;
    }

    public <T extends IChannel>T getChannel(Class<T> cs) throws Exception {
        Constructor<T> constructor = cs.getConstructor(SshSessionEntry.class);
        T iChannel = constructor.newInstance(this);
        iChannel.open();
        return iChannel;
    }

    public <T>T getAttribute(AttributeRepository.AttributeKey<T> attributeKey) {
        return session.getAttribute(attributeKey);
    }


    @Override
    public void close() throws IOException {
        session.close();
    }
}
